import java.util.concurrent.Exchanger;

public class RunExchanger {
    public static void main(String[] args) {
        final Exchanger exchanger = new Exchanger();
        new Thread(){
            @Override
            public void run() {
                trade("火箭队","姚明",exchanger);
                getTeamState("火箭队");
            }
        }.start();
        new Thread(){
            @Override
            public void run() {
                trade("马刺队","邓肯",exchanger);
                getTeamState("马刺队");
            }
        }.start();
        new Thread(){
            @Override
            public void run() {
                trade("湖人队","科比",exchanger);
                    getTeamState("湖人队");

            }
        }.start();
        new Thread(){
            @Override
            public void run() {
                trade("勇士队","库里",exchanger);
                getTeamState("勇士队");
            }
        }.start();
        new Thread(){
            @Override
            public void run() {
                trade("骑士队","詹姆士",exchanger);
                getTeamState("骑士队");
            }
        }.start();

    }
    //交换线程中的变量值，在没有交换到变量时，此线程会一直等待
    private static void trade(String team,String player,Exchanger exchanger){
        try{
            System.out.println(Thread.currentThread().getId()+","+team+"准备转让"+player);
            int rand = (int)(Math.random()*10000);
            Thread.sleep(rand);
            String info = (String) exchanger.exchange(player);
            System.out.println(rand/1000+"秒后"+Thread.currentThread().getId()+","+team+"得到了"+info);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
    private static void getTeamState(String team){
//        while(Thread.currentThread().getState().toString() != "RUNNABLE") {
            System.out.println(Thread.currentThread().getId() + ", " + team + "状态：" + Thread.currentThread().getState());
//        }

    }

}
